package com.zhehekeji.opsys.api.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName LogAdvice
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2015-3-26   上午10:28:58
 */
@Aspect
public class LogAdvice {
	
	private static final Logger logger = LoggerFactory.getLogger(LogAdvice.class);
	
	@Around(value="PointcutsDefinition.logPointcutDef()")
	public Object log(ProceedingJoinPoint pj){
		String methodName = pj.getSignature().getName();
		inlog(pj.getArgs(), methodName);
		Object result = null;
		try {
			result = pj.proceed(pj.getArgs());
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
		}
		outParameters(result, methodName);
		return result;
	}
	
	private void inlog(Object[] parameters, String methodName){
		StringBuilder logBuilder = new StringBuilder(methodName);
		logBuilder.append(" method is called");
		if (parameters == null || parameters.length < 1){
			logger.info(logBuilder.toString());
		}else{
			logBuilder.append(", Print entrance parameters:");
			for (Object parameter : parameters){
				logBuilder.append(parameter).append(",");
			}
			logBuilder.deleteCharAt(logBuilder.length() - 1);
			logger.info(logBuilder.toString());
		}
	}
	
	public void outParameters(Object result, String methodName){
		StringBuilder logBuilder = new StringBuilder();
		logBuilder.append("End of the ").append(methodName).append(" call");
		if (result != null){
			logBuilder.append(", Print the export parameters:").append(result);
		}
		logger.info(logBuilder.toString());
	}
}
